package com.pokermind.common.log;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 结构化日志工具类
 * 用于生成格式化的日志输出
 * 
 * @author PokerMind Team
 */
public class PlainLog {
    
    private final Map<String, Object> fields;
    
    public PlainLog() {
        this.fields = new LinkedHashMap<>();
    }
    
    public PlainLog(String key, Object value) {
        this();
        put(key, value);
    }
    
    /**
     * 添加字段
     */
    public PlainLog put(String key, Object value) {
        fields.put(key, value);
        return this;
    }
    
    /**
     * 添加多个字段
     */
    public PlainLog putAll(Map<String, Object> map) {
        if (map != null) {
            fields.putAll(map);
        }
        return this;
    }
    
    /**
     * 移除字段
     */
    public PlainLog remove(String key) {
        fields.remove(key);
        return this;
    }
    
    /**
     * 获取字段值
     */
    public Object get(String key) {
        return fields.get(key);
    }
    
    /**
     * 检查是否包含字段
     */
    public boolean contains(String key) {
        return fields.containsKey(key);
    }
    
    /**
     * 清空所有字段
     */
    public PlainLog clear() {
        fields.clear();
        return this;
    }
    
    /**
     * V4.7: 获取所有字段（用于日志重组）
     */
    public Map<String, Object> getFields() {
        return new LinkedHashMap<>(fields);
    }
    
    /**
     * V4.7: 遍历所有字段
     */
    public void forEach(java.util.function.BiConsumer<String, Object> action) {
        fields.forEach(action);
    }
    
    /**
     * 生成日志字符串
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        
        boolean first = true;
        for (Map.Entry<String, Object> entry : fields.entrySet()) {
            if (!first) {
                sb.append(", ");
            }
            first = false;
            
            sb.append(entry.getKey()).append(":");
            Object value = entry.getValue();
            if (value == null) {
                sb.append("null");
            } else if (value instanceof String) {
                sb.append(value);
            } else {
                sb.append(value.toString());
            }
        }
        
        sb.append("]");
        return sb.toString();
    }
    
    /**
     * 创建新的PlainLog实例
     */
    public static PlainLog of(String key, Object value) {
        return new PlainLog(key, value);
    }
    
    /**
     * 创建空的PlainLog实例
     */
    public static PlainLog create() {
        return new PlainLog();
    }
}